import { defineComponent, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Cookies from 'js-cookie'
import { Checkbox, FormTab } from '@formily/element-plus'
import { createForm } from '@formily/core'
import { ElButton } from 'element-plus'
import { useRequest } from 'ahooks-vue'
import { connect, mapProps } from '@formily/vue'
import { decrypt, encrypt } from '@/utils/jsencrypt'
import useUserStore from '@/store/modules/user'
import SchemaForm from '@/components/SchemaForm/index'
import SvgIcon from '@/components/SvgIcon/index.vue'
import PhoneCaptcha from '@/views/PhoneCaptcha.vue'
import './login.scss'

export default defineComponent({
  setup() {
    const title = ref('学生信息查询系统')
    const userStore = useUserStore()
    const route = useRoute()
    const router = useRouter()
    let activeKey = 't1'
    const formTab = FormTab.createFormTab(activeKey)

    const form = createForm()
    const redirect = ref<string>()

    watch(route, (newRoute) => {
      redirect.value = newRoute.query && newRoute.query.redirect as string
    }, { immediate: true })

    const { run: doLogin, loading } = useRequest(userStore.login, { manual: true })
    const handleLogin = async () => {
      form.clearErrors()
      await form.validate(`collapse.${activeKey}.*`)
      const values = form.getValuesIn(`collapse.${activeKey}.*`)
      if (activeKey === 't1') {
        const { username, password, rememberMe } = values
        if (rememberMe) {
          Cookies.set('username', username, { expires: 30 })
          Cookies.set('password', encrypt(password), { expires: 30 })
          Cookies.set('rememberMe', rememberMe, { expires: 30 })
        }
        else {
          // 否则移除
          Cookies.remove('username')
          Cookies.remove('password')
          Cookies.remove('rememberMe')
        }
        await doLogin({ username, password, type: activeKey })
      }
      const query = route.query
      const otherQueryParams = Object.keys(query).reduce(
        (acc, cur) =>
          ({ ...acc, [cur]: cur === 'redirect' ? (void 0) : cur }),
        {},
      )
      void router.push({ path: redirect.value || '/', query: otherQueryParams })
    }

    function getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      const rememberMe = Boolean(Cookies.get('rememberMe'))
      if (username && password) {
        form.setValues({
          username,
          password: decrypt(password),
          rememberMe,
        }, 'overwrite')
      }
    }
    getCookie()

    const schema = {
      type: 'object',
      properties: {
        collapse: {
          'type': 'void',
          // 'x-component': 'FormTab',
          // 'x-component-props': {
          //   formTab,
          //   beforeLeave(tabName: string) {
          //     activeKey = tabName
          //   },
          // },
          'properties': {
            t1: {
              'type': 'void',
              // 'x-component': 'FormTab.TabPane',
              // 'x-component-props': {
              //   label: '账号登陆',
              //   name: 't1',
              // },
              'properties': {
                username: {
                  'type': 'string',
                  'x-component': 'Input',
                  'x-decorator': 'FormItem',
                  'required': true,
                  'x-component-props': {
                    type: 'text',
                    size: 'large',
                    autoComplete: 'off',
                    placeholder: '账号',
                  },
                  'x-content': {
                    prefix: () => <SvgIcon iconClass="user" class="el-input__icon input-icon" />,
                  },
                },
                password: {
                  'type': 'string',
                  'x-component': 'Input',
                  'x-decorator': 'FormItem',
                  'required': true,
                  'x-component-props': {
                    type: 'password',
                    size: 'large',
                    autoComplete: 'off',
                    placeholder: '密码',
                  },
                  'x-content': {
                    prefix: () => <SvgIcon iconClass="password" class="el-input__icon input-icon" />,
                  },
                },
                rememberMe: {
                  'type': 'boolean',
                  'x-component': 'Checkbox',
                  'x-content': {
                    default: () => '记住密码',
                  },
                },
              },
            },
            // t2: {
            //   'type': 'void',
            //   'x-component': 'FormTab.TabPane',
            //   'x-component-props': {
            //     label: '验证码登录',
            //     name: 't2',
            //   },
            //   'properties': {
            //     tel: {
            //       'type': 'string',
            //       'x-component': 'Input',
            //       'x-decorator': 'FormItem',
            //       'required': true,
            //       'x-component-props': {
            //         type: 'text',
            //         size: 'large',
            //         autoComplete: 'off',
            //         placeholder: '手机号',
            //         maxlength: 11,
            //       },
            //       'x-content': {
            //         prefix: () => <SvgIcon iconClass="phone" class="el-input__icon input-icon" />,
            //       },
            //     },
            //     code: {
            //       'type': 'string',
            //       'x-component': connect(PhoneCaptcha, mapProps({ value: 'modelValue' }, props => ({ ...props, 'onUpdate:modelValue': props.onChange }))),
            //       'x-decorator': 'FormItem',
            //       'required': true,
            //       'x-reactions': {
            //         dependencies: ['.tel'],
            //         fulfill: {
            //           schema: {
            //             'x-component-props': {
            //               phone: '{{$deps[0]}}',
            //             },
            //           },
            //         },
            //       },
            //     },
            //   },
            // },
          },
        },
      },
    }

    return () => (
      <div class="login">
        <div class="login-form">
          <h3 class="title">
            {title.value}
          </h3>
          <SchemaForm form={form} schema={schema} components={{ Checkbox }} scope={{ formTab }} />
          <ElButton
            loading={loading.value}
            size="large"
            type="primary"
            class="w-full mt-2"
            onClick={handleLogin}
          >
            {loading.value ? <span>登 录 中...</span> : <span>登 录</span>}
          </ElButton>
        </div>

        <div class="el-login-footer">
          <span>
            Copyright ©
            <a
              href="https://beian.miit.gov.cn/state/outPortal/loginPortal.action/#/Integrated/recordQuery"
            >
              黔ICP备2024034961号
            </a>
            {' '}
            All Rights Reserved.
          </span>
        </div>
      </div>
    )
  },
})
